package com.ctsi.framework.mybatis.dialect;

import java.sql.PreparedStatement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * sql server 2000
 * @author zhangjw
 */
public class MsSqlDialect extends AbstractMiDialect{


	static final Pattern Select_PATTERN = Pattern.compile("\\b(select\\s)", Pattern.CASE_INSENSITIVE);
	
	
	static final Pattern SelectDis_PATTERN = Pattern.compile("\\b(select\\s{0,}distinct\\s)", Pattern.CASE_INSENSITIVE);
	
	static int getSelectPos(String sql){
		Matcher m=Select_PATTERN.matcher(sql);
		boolean f=m.find();
		if(f){
			return m.start();
		}
		return -1;
	}

	static int getAfterSelectInsertPoint(String sql) {
 
		int selectIndex = getSelectPos(sql);
		int selectDistinctIndex=-1;
		Matcher m=SelectDis_PATTERN.matcher(sql);
		boolean f=m.find();
		int len=15;
		if(f){
			selectDistinctIndex= m.start();
			len=m.end()-selectDistinctIndex-1;
		}
		
		
 
		return selectIndex + (selectDistinctIndex == selectIndex ? len : 6);
	}

	@Override
	public void setLimitParamters(PreparedStatement ps, int parameterSize,
			int offset, int limit) {
		/**
		 * 需要查询出最大的数据后由Mybatis保留offset的数据来操作偏移的量
		 */
//		ps.setInt(parameterSize + 1, offset + limit);
	}

	@Override
	public String getLimitString(String sql, int offset) {
		if (!(offset >= 0))
			throw new UnsupportedOperationException("sql server has no offset");
		return new StringBuilder(sql.length() + 16).append(sql).insert(getAfterSelectInsertPoint(sql), " top " + offset).toString();
	}


	@Override
	public boolean supportsLimitOffset() {
		
		return false;
	}

}
